<template>
	<div class="page-container">
		<!-- 存储提醒 -->
		<div class="storage-reminder">
			<img src="https://gd-hbimg.huaban.com/2b3f65915379eec0d0fe43ed34fd2a882623cf5de42cd-Rv2DMa_fw658" alt="存储图标"
				class="storage-icon">
			<div class="storage-details">
				<p class="storage-title">您的可用空间</p>
				<p class="storage-usage">共 1GB 已使用 899MB</p>
			</div>
		</div>

		<!-- 模板列表 -->
		<ul class="template-list">
			<li v-for="item,index in fileList" :key="index" class="template-item">
				<img :src="item.headerImage || 'https://mp-7f09bcd1-475b-4778-8767-52ae180f55ab.cdn.bspapp.com/cloudstorage/美化界面.png'"
					alt="模板预览" class="template-preview">
				<div class="template-info" @click='lookFile(item)'>
					<p class="template-name">{{item.fileName}}</p>
					<p class="template-size">大小：{{item.size}}MB</p>
				</div>
				<div class="template-actions">
					<span v-if="!option.type" @click="cross_fun(item)" class="delete-icon"><van-icon
							name="cross" /></span>
					<span v-if="option.type" @click="selectTemplate(item)" class="select-icon"><van-icon
							name="success" /></span>
				</div>
			</li>

			<van-empty description="暂无模板" v-if='fileList.length == 0' />
		</ul>

		<!-- 添加文件按钮 -->
		<div class="add-button" @click="addFile_fun" v-if="!option.type">
			<van-icon name="plus" />
		</div>

		<!-- 上传文件弹窗 -->
		<van-popup 
			:show="isShowPopup" 
			position="bottom" 
			custom-style="height: 60%; border-radius: 10px 10px 0 0;" 
			@click-overlay="isShowPopup = false"
		>
			<div class="popup-content">
				<van-cell-group>
					<van-field :value="addFile.fileName" placeholder="请输入文件名" label="文件名称" input-align="right"
						@change="changeInput($event, 'fileName')" />

					<van-field label="预览图" readonly input-align="right">
						<van-uploader :file-list="fileList_preview" max-count="1" @delete="deleteImages"
							@after-read="afterRead($event, 1)" slot="button" />
					</van-field>

					<van-field label="文件上传" readonly input-align="right">
						<van-uploader @after-read="afterRead($event, 2)" accept='file' slot="button">
							<button type="primary" class="upload-file-btn">
								<van-icon name="back-top" style="margin-right: 8px;" />
								<span>上传文件</span>
							</button>
						</van-uploader>
					</van-field>
				</van-cell-group>
				<button type="primary" @click='save' class="save-btn">保存</button>
			</div>
		</van-popup>
	</div>
</template>

<script>
	export default {
		data() {
			return {
				isShowPopup: false,
				addFile: {
					url: '',
					fileName: ''
				},
				fileList: [],
				fileList_preview: [],
				progress: 0,
				option: {}
			}
		},

		onLoad(option) {
			this.option = option
			this.getInit()
		},

		methods: {
			async getInit() {
				let result = await this.$axios('overallSituation', {
					state: 'look',
					databaseName: "templateManagement",
				}, true)

				if (result.code == 200) {
					this.fileList = result.data || []
				}
			},

			// 添加文件
			addFile_fun() {
				this.$set(this, 'addFile', {})
				// 跳转到添加文件页面
				this.isShowPopup = true
			},

			// 点击预览
			lookFile(item) {
				let downloadFile = uni.downloadFile({
					url: item.url,
					success: res => {
						uni.hideLoading()
						uni.openDocument({
							filePath: res.tempFilePath,
							showMenu: true, //允许分享
						})
					}
				})

				downloadFile.onProgressUpdate(res => {
					this.progress = res.progress
					uni.showLoading({
						title: "正在打开" + this.progress + '%',
					})
				})
			},

			// 上传图片/模板
			async afterRead(e, type) {
				console.log(e);

				// 如果上传的是文件 判断文件类型
				if (type == 2) {
					if (!['docx', 'doc'].includes(e.detail.file.name.split(".")[1])) {
						uni.showToast({
							title: "请上传 word 文件",
							icon: "none",
							duration: 2000
						})
						return
					}
				}

				uni.showLoading({
					title: type == 1 ? "上传中" : "正在解析 word",
				})

				// 将地址转为线上的
				let imageRes = await uniCloud.uploadFile({
					filePath: e.detail.file.url,
					cloudPath: type == 2 ? e.detail.file.name : '模板预览图',
					header: {
						"Content-Type": "multipart/form-data"
					},
				})

				if (type == 1) {
					this.addFile.headerImage = imageRes.fileID
					this.fileList_preview = [{
						url: imageRes.filePath
					}]
				} else {
					let result = await this.$axios('getWordContent', {
						url: imageRes.fileID
					}, false)
					// this.addFile.jsonString = result.data //解析 word 文档 获取 json 数据
					this.$set(this.addFile, 'jsonString', result.data)
					this.$set(this.addFile, 'url', imageRes.fileID)
					this.$set(this.addFile, 'fileName', e.detail.file.name.split('.')[0])
					this.$set(this.addFile, 'size', (e.detail.file.size / 1024 / 1024).toFixed(2))
					// this.addFile.url = imageRes.fileID
					// this.addFile.fileName = e.detail.file.name.split('.')[0]
					// this.addFile.size = (e.detail.file.size / 1024 / 1024).toFixed(2)
				}

				uni.hideLoading()
			},

			async save() {
				// 上传到数据库
				let result = await this.$axios('overallSituation', {
					state: 'add',
					databaseName: "templateManagement",
					...this.addFile
				}, false)

				this.isShowPopup = false
				this.getInit()
			},

			// 删除模板
			cross_fun(item) {
				uni.showModal({
					title: '提示',
					content: '您确定删除这个模板吗？',
					confirmText: "确定", //这块是确定按钮的文字
					cancelText: "取消", //这块是取消的文字
					success: async (res) => {
						if (res.confirm) {
							let result = await this.$axios('overallSituation', {
								state: 'delete',
								databaseName: "templateManagement",
								_id: item._id
							}, true)

							if (result.code == 200) {
								this.getInit()
							}
						}
					},
				})
			},

			// 选择模板
			selectTemplate(item) {
				uni.$emit('refreshPreviousPage', {
					id: item._id
				});
				uni.navigateBack({
					delta: 1,
				});
			},

			// 输入框内容发生变化
			changeInput(e, str) {
				this.addFile[str] = e.detail;
			},
		}
	}
</script>

<style scoped>
	.page-container {
		display: flex;
		flex-direction: column;
		align-items: center;
		background-color: #f9f9f9;
		min-height: 100vh;
		padding: 20px;
		box-sizing: border-box;
	}

	.storage-reminder {
		width: 100%;
		background-color: #3498db;
		border-radius: 10px;
		box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
		display: flex;
		align-items: center;
		padding: 15px;
		margin-bottom: 20px;
	}

	.storage-icon {
		width: 40px;
		height: 40px;
		border-radius: 50%;
		margin-right: 15px;
	}

	.storage-details {
		color: white;
	}

	.storage-title {
		font-size: 16px;
		font-weight: 600;
		margin-bottom: 5px;
	}

	.storage-usage {
		font-size: 14px;
		font-weight: 400;
	}

	.template-list {
		width: 100%;
		flex: 1;
		overflow-y: auto;
		margin-bottom: 20px;
	}

	.template-item {
		background-color: white;
		border-radius: 8px;
		box-shadow: 0 3px 5px rgba(0, 0, 0, 0.1);
		display: flex;
		align-items: center;
		padding: 10px;
		margin-bottom: 15px;
	}

	.template-preview {
		width: 40px;
		height: 40px;
		border-radius: 50%;
		margin-right: 15px;
	}

	.template-info {
		flex: 1;
	}

	.template-name {
		font-size: 16px;
		font-weight: 600;
		margin-bottom: 5px;
	}

	.template-size {
		font-size: 14px;
		font-weight: 400;
		color: #999;
	}

	.template-actions {
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 20px;
		margin-left: 15px;
	}

	.add-button {
		width: 50px;
		height: 50px;
		border-radius: 50%;
		background-color: #3498db;
		display: flex;
		align-items: center;
		justify-content: center;
		color: white;
		font-size: 20px;
		font-weight: 700;
		position: fixed;
		bottom: 20px;
		right: 20px;
		box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
		cursor: pointer;
	}

	.popup-content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: space-around;
		padding: 20px;
		background-color: white;
		border-radius: 10px;
		box-shadow: 0 -4px 6px rgba(0, 0, 0, 0.1);
	}

	.upload-file-btn {
		width: 120px;
		height: 35px;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 14px;
		font-weight: 700;
		background-color: #3498db;
		color: white;
		border-radius: 5px;
		cursor: pointer;
	}



	.save-btn {
		width: 95%;
		height: 35px;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 12px;
		font-weight: 700;
		background-color: #2ecc71;
		color: white;
		border-radius: 5px;
		position: fixed;
		bottom: 10px;
		left: 50%;
		transform: translateX(-50%);
	}
</style>